def optimal_path(distance_matrix, path):
    n = len(path)
    is_optimal = False

    while not is_optimal:
        is_optimal = True
        for i in range(n - 1):
            for j in range(i + 1, n):
                # Calculate the current total distance with these edges
                current_distance = distance_matrix[path[i], path[i + 1]] + distance_matrix[path[j], path[j + 1]] \
                    if j < n - 1 else distance_matrix[path[i], path[i + 1]]

                # Calculate the new total distance if we swap path[i+1] and path[j]
                new_distance = distance_matrix[path[i], path[j]] + distance_matrix[path[i + 1], path[j + 1]] \
                    if j < n - 1 else distance_matrix[path[i], path[j]]

                if new_distance < current_distance:
                    # Perform the swap
                    path[i + 1], path[j] = path[j], path[i + 1]

                    # Mark that a change was made, so we need to check the path again
                    is_optimal = False

    return path


# 示例用法
distance_matrix = [
    [0, 10, 15, 20],
    [10, 0, 35, 25],
    [15, 35, 0, 30],
    [20, 25, 30, 0]
]

initial_path = [0, 1, 2, 3]
optimal_path_result = optimal_path(distance_matrix, initial_path)
print("Optimal Path:", optimal_path_result)